package com.campus.help.utils;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 微信AES解密工具类
 *
 * @author campus-help
 * @since 2025-09-18
 */
@Slf4j
public class WechatAESUtils {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    /**
     * AES解密
     *
     * @param encryptedData 加密数据
     * @param sessionKey 会话密钥
     * @param iv 初始向量
     * @return 解密后的数据
     */
    public static String decrypt(String encryptedData, String sessionKey, String iv) {
        try {
            byte[] dataByte = Base64.getDecoder().decode(encryptedData);
            byte[] keyByte = Base64.getDecoder().decode(sessionKey);
            byte[] ivByte = Base64.getDecoder().decode(iv);

            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            SecretKeySpec spec = new SecretKeySpec(keyByte, ALGORITHM);
            IvParameterSpec ivSpec = new IvParameterSpec(ivByte);

            cipher.init(Cipher.DECRYPT_MODE, spec, ivSpec);

            byte[] decryptedByte = cipher.doFinal(dataByte);
            return new String(decryptedByte, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("AES解密失败", e);
            throw new RuntimeException("AES解密失败", e);
        }
    }
}
